
package artid.com.arttogo.activity;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.webkit.WebView.HitTestResult;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.Volley;
import artid.com.arttogo.R;
import artid.com.arttogo.activity.BaseActivity;
import artid.com.arttogo.adapter.ListAdapter;
import artid.com.arttogo.adapter.MallListAdapter;
import artid.com.arttogo.bean.GcGoodslist;
import artid.com.arttogo.bean.GoodsList;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.BitmapCache;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.utils.MySharedPreferences;
import artid.com.arttogo.utils.NetUtils;
import artid.com.arttogo.utils.VeDate;
import artid.com.arttogo.view.pulllist.PullToRefreshLayout;
import artid.com.arttogo.view.pulllist.PullableListView;
import artid.com.arttogo.view.xlistview.PLA_AbsListView;
import artid.com.arttogo.view.xlistview.PLA_AdapterView;
import artid.com.arttogo.view.xlistview.XListView;


/**
 *
 * 类名称：ArtMallActivity
 * 类描述：商城首页
 * 创建人：耿卫斌
 * 创建时间：2017/5/22 16:59
 *
 */
public class ArtMallActivity extends BaseActivity implements OnClickListener {
    String TAG_CACHE_VIEW = "mallViewCache";
    String TAG_CACHE_CATE = "mallCateCache";
    MySharedPreferences mSharePre;
    private Context mContext;
    private XListView mListView;
    private MallListAdapter adapter;
    private ImageView back;
    private List<GoodsList> list;
    private TextView title;
    int pageIndex = 1;
    String strType = "";
    private ImageLoader mImageLoader;
    int  pagesize = 20;
    private LinearLayout mLinearLayout;
    /** 屏幕宽度 */
    private int mScreenWidth;
    /** 导航条目宽度 */
    private int item_width;
    List<GcGoodslist> typeList;
    int endPosition = 0,beginPosition,currentFragmentIndex;
    ImageView mImageView;
    /** 导航栏 */
    private HorizontalScrollView mHorizontalScrollView;
    LinearLayout blankView;
    /*
     * (non-Javadoc)
     *
     * @see com.sigmatrix.artworkart.BaseActivity#onCreate(android.os.Bundle)
     */
    private String imgwide;// 请求的图片宽度
    private int dataNum;//数据总条数
    private Boolean isLoad = true;//是否加载数据（默认可以加载）
    String strMallViewCache;//视图的缓存
    String strMallCateCache;//类目的缓存

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_artmall);
        mContext = ArtMallActivity.this;
        mSharePre = MySharedPreferences.getMySharedPreferences(mContext);
        imgwide = (Integer.parseInt(NetUtils.getDisplayMetrics((Activity) mContext).get(NetUtils.DM_WIDTH)) / 2) + "";
        blankView = (LinearLayout)findViewById(R.id.ll_hint);
        ImageView imageBlank = (ImageView)blankView.findViewById(R.id.img_blank);
        imageBlank.setImageResource(R.drawable.blank_mall);
        ViewGroup.LayoutParams lp = imageBlank.getLayoutParams();
        lp.width = LayoutParams.WRAP_CONTENT;
        lp.height = LayoutParams.WRAP_CONTENT;
        imageBlank.setLayoutParams(lp);
        blankView.setVisibility(View.GONE);
        TextView textBlank = (TextView)blankView.findViewById(R.id.text_blank);
        textBlank.setText("暂无出售商品");
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mScreenWidth = dm.widthPixels;
        item_width = (int) ((mScreenWidth  / 5.0 ));
        mImageView = (ImageView) findViewById(R.id.img1);
        mImageView.getLayoutParams().width = item_width;
        mListView = (XListView) findViewById(R.id.ArtMall_listivew);
        mListView.setVisibility(View.GONE);
        mListView.setPullRefreshEnable(true);
        mListView.setPullLoadEnable(true);
        mListView.setXListViewListener(mIXListViewListener);
        mListView.setOnScrollListener(mOnScrollListener);
//        listview = (ListView) findViewById(R.id.listview1);
        back = (ImageView) findViewById(R.id.title_back);
        title = (TextView) findViewById(R.id.tv_text);
        RequestQueue mQueue = Volley.newRequestQueue(mContext);
        mImageLoader = new ImageLoader(mQueue, new BitmapCache());
        mLinearLayout = (LinearLayout) findViewById(R.id.hsv_content);
        mHorizontalScrollView = (HorizontalScrollView) findViewById(R.id.hsv_view);
        back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                finish();
            }
        });
        loading = (RelativeLayout) findViewById(R.id.rel_progressbar);
        loading.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                System.out.println("#zhebiceng");
            }
        });
        strMallCateCache = mSharePre.getValue(TAG_CACHE_CATE,"");
        if (!TextUtils.isEmpty(strMallCateCache)){
            setCateDate(strMallCateCache);
        }
        strMallViewCache = mSharePre.getValue(TAG_CACHE_VIEW,"");
        if (!TextUtils.isEmpty(strMallViewCache)){
            setMainReqDate(strMallViewCache);
        }

//		AppUrl.newsList(AuthNewsletterActivity.this);
//		requestGradeList();
        requestCategoryList();
        requestGradeList(true);
    }


    //实现瀑布流下拉刷新上拉加载监听
    XListView.IXListViewListener mIXListViewListener = new XListView.IXListViewListener() {
        @Override
        public void onRefresh() {
            // 下拉刷新
            pageIndex++;
            requestGradeList(true);
        }

        @Override
        public void onLoadMore() {
            // 上拉加载
            pageIndex = 1;
            requestGradeList(false);
        }
    };

    //实现瀑布流滑动监听
    XListView.OnScrollListener mOnScrollListener = new XListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(PLA_AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(PLA_AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if(list!=null && list.size()!=0) {
                Log.d("log","firstVisibleItem:"+firstVisibleItem+"===visibleItemCount:"+visibleItemCount+"===totalItemCount:"+totalItemCount);
                if (list.size() != dataNum && isLoad == true) {
                    //-11是数据已经显示一半的时候如果加头了就-12
                    //-12是数据已经显示一半的时候（因为是瀑布流并且加了头所以-12）
                    if (pageIndex == 1 && firstVisibleItem == (pagesize - 11)) {
                        pageIndex++;
                        requestGradeList(false);
                    } else if (((pageIndex * pagesize) - 11) == firstVisibleItem) {
                        pageIndex++;
                        requestGradeList(false);
                    }
                }
            }
        }
    };


    private void initNav(List<GcGoodslist> list) {
//		String[] arrTag = {"简介","动态","在售","资讯"};
        mLinearLayout.removeAllViews();
        for (int i = 0; i < list.size(); i++) {
            RelativeLayout layout = new RelativeLayout(this);
            TextView view = new TextView(this);
            view.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
            view.setText(list.get(i).getGc_name());
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.CENTER_IN_PARENT);
            layout.addView(view, params);
            mLinearLayout.addView(layout, item_width, VeDate.dip2px(mContext, 40));
            layout.setOnClickListener(this);
            layout.setTag(i);
        }
    }

    @Override
    public void onClick(View v) {
        int position = (Integer) v.getTag();
        strType = typeList.get(position).getGc_id();

        Animation animation = new TranslateAnimation(endPosition* item_width, position
                * item_width, 0, 0);

        beginPosition = position * item_width;

        currentFragmentIndex = position;
        if (animation != null) {
            animation.setFillAfter(true);
            animation.setDuration(0);
            mImageView.startAnimation(animation);
            mHorizontalScrollView.smoothScrollTo((currentFragmentIndex - 1)
                    * item_width, 0);
        }
        endPosition = position;
        pageIndex =1;
        requestGradeList(true);
    }
    private void requestCategoryList() {
        VolleyBasic.getInstance(ArtMallActivity.this).post(Cache.gcGoodslist, VolleyMap.getInstance().gcGoodslist(), GcGoodslist.class,
                new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        if (pageIndex==1)
                        mSharePre.setValue(TAG_CACHE_CATE,vd.getJson());

                        setCateDate(vd.getJson());
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub

                    }
                });
    }
    void setCateDate(String json){
        VolleyData vd = new VolleyData(json,GcGoodslist.class);
        System.out.println(vd.getJson());
//						Toast.makeText(mContext, vd.getJson(), 2).show();
        @SuppressWarnings("unchecked")
        final List<GcGoodslist> list = (List<GcGoodslist>) vd.getList();
        typeList = list;
        initNav(list);
    }
    View headView = null;
    JSONObject mainJson;
    JSONArray mainJSONArr;
    private void requestGradeList(Boolean isLoadDialog) {
        isLoad = false;
        if (isLoadDialog) {
            VolleyBasic.showLoding(this);
        }
        VolleyBasic.getInstanceNoDialog(ArtMallActivity.this).post(Cache.goodsList, VolleyMap.getInstance().goodsList(
                pageIndex,pagesize, strType,imgwide,"1"), GoodsList.class,
                new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        if (pageIndex==1)
                        mSharePre.setValue(TAG_CACHE_VIEW,vd.getJson());

                        setMainReqDate(vd.getJson());

                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                        isLoad = true;
                        mListView.stopRefresh();
                        mListView.stopLoadMore();
                    }
                });
    }
    void setMainReqDate(String json){
        VolleyData vd = new VolleyData(json,GoodsList.class);
        isLoad = true;
        mListView.stopRefresh();
        mListView.stopLoadMore();
        list = (List<GoodsList>) vd.getList();
        JSONObject jsonString = vd.getObj();
        JSONArray jsonArray = jsonString.optJSONArray("data");
        if (list.isEmpty()) {
            if (pageIndex==1) {
                mListView.setVisibility(View.INVISIBLE);
                blankView.setVisibility(View.VISIBLE);
            }
            return;
        }
        mListView.setVisibility(View.VISIBLE);
        blankView.setVisibility(View.GONE);
        if (mListView.getVisibility()==View.INVISIBLE) {
            mListView.setVisibility(View.VISIBLE);
        }
        if(pageIndex==1) {
            try {

                JSONObject jsonObject = new JSONObject(vd.getJson());
                dataNum = jsonObject.getInt("num");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (pageIndex!=1) {
            try {
                if (jsonArray==null) {
                    return;
                }
                for (int i = 0; i < jsonArray.length(); i++) {

                    mainJSONArr.put(jsonArray.get(i));

                }
                mainJson.remove("data");
                mainJson.put("data", mainJSONArr);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            adapter.addlist(list);
            setItemClick(mainJson.toString());
            return;
        }
        mainJson = jsonString;
        mainJSONArr = jsonArray;
        adapter = new MallListAdapter(mContext);
        adapter.setdata(list);
        mListView.setAdapter(adapter);
        setItemClick(vd.getJson());
    }



    void setItemClick(final String json){
        mListView.setOnItemClickListener(new PLA_AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(PLA_AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, MallDetailPagerActivity.class);
                intent.putExtra("id",json);
                intent.putExtra("index", position-1);
                startActivity(intent);
            }
        });
    }


}
